package com.wtwd.wtwddevice.listener.deviceServerMsg.handler.impl;

import com.wtwd.device.annotation.MsgType;
import com.wtwd.device.constant.AnswerStateEnum;
import com.wtwd.device.constant.CmdStateEnum;
import com.wtwd.device.constant.MsgTypeEnum;
import com.wtwd.device.mqtentity.MessageBase;
import com.wtwd.device.protocol.AppProtocol;
import com.wtwd.device.protocol.WTProtocol;
import com.wtwd.wtwddevice.listener.deviceServerMsg.handler.IMsgHandler;
import com.wtwd.wtwddevice.service.IAppCommService;
import com.wtwd.wtwddevice.service.IDeviceService;
import com.wtwd.wtwddevice.service.IDeviceWPhoneService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@MsgType(MsgTypeEnum.W_PHL)
@Component
public class WPhoneHandlerImpl implements IMsgHandler {


    @Resource
    private IDeviceService deviceService;

    @Resource
    private IDeviceWPhoneService deviceWPhoneService;

    @Resource
    private IAppCommService appCommService;

    @Override
    public void handleMsg(MessageBase messageBase) {
        WTProtocol wtProtocol = messageBase.getWtProtocol();
        String number = wtProtocol.getNumber();
        Integer state = Integer.valueOf(wtProtocol.getBody());
        if (state.equals(AnswerStateEnum.NORMAL.getState())){
            Long deviceId = deviceService.getDeviceIdByImei(wtProtocol.getImei());
            if (deviceWPhoneService.isTagDeletion(deviceId,number)){//因为是全量发送,只要存在标记删除的号码,则可以全部删除
                deviceWPhoneService.deleteByDeviceId(deviceId);
            }else {
                deviceWPhoneService.updateState(deviceId,number, CmdStateEnum.SUCCESS.getState());
            }
            AppProtocol protocol = AppProtocol.builder()
                    .imei(wtProtocol.getImei())
                    .cmdName(MsgTypeEnum.APP_W_PHL.getCmdName())
                    .state(AnswerStateEnum.NORMAL.getState())
                    .data(null)
                    .build();
            appCommService.pushDeviceState(deviceId, protocol);
        }
    }


}
